const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

/**
 * 云函数入口
 */
exports.main = async (event, context) => {
  const { action, data } = event
  const wxContext = cloud.getWXContext()

  try {
    // 验证管理员权限
    const hasPermission = await checkAdminPermission(wxContext.OPENID)
    if (!hasPermission) {
      return {
        success: false,
        code: 403,
        message: '权限不足，仅管理员可操作'
      }
    }

    // 路由分发
    switch (action) {
      case 'getStats':
        return await getStats()
      case 'getList':
        return await getList()
      case 'create':
        return await createInviteCode(data, wxContext.OPENID)
      case 'update':
        return await updateInviteCode(data)
      case 'toggleStatus':
        return await toggleStatus(data)
      case 'delete':
        return await deleteInviteCode(data)
      default:
        return {
          success: false,
          code: 400,
          message: '无效的操作类型'
        }
    }
  } catch (error) {
    console.error('邀请码管理云函数错误:', error)
    return {
      success: false,
      code: 500,
      message: error.message || '服务器错误'
    }
  }
}

/**
 * 检查管理员权限
 */
async function checkAdminPermission(openid) {
  try {
    const { data } = await db.collection('users')
      .where({ openid, role: 'admin' })
      .limit(1)
      .get()
    
    return data.length > 0
  } catch (error) {
    console.error('权限检查失败:', error)
    return false
  }
}

/**
 * 获取统计信息
 */
async function getStats() {
  try {
    // 获取总数和启用数
    const { total: totalCodes } = await db.collection('invite_codes').count()
    const { total: activeCodes } = await db.collection('invite_codes')
      .where({ status: 'active' })
      .count()

    // 获取累计使用次数
    const { data: codeList } = await db.collection('invite_codes')
      .field({ usedCount: true })
      .get()
    const usedCount = codeList.reduce((sum, item) => sum + (item.usedCount || 0), 0)

    // 获取今日使用次数
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    const { total: todayUsed } = await db.collection('invite_records')
      .where({
        createTime: _.gte(today)
      })
      .count()

    return {
      success: true,
      data: {
        totalCodes,
        activeCodes,
        usedCount,
        todayUsed
      }
    }
  } catch (error) {
    console.error('获取统计失败:', error)
    throw error
  }
}

/**
 * 获取邀请码列表
 */
async function getList() {
  try {
    const { data } = await db.collection('invite_codes')
      .orderBy('createTime', 'desc')
      .get()

    return {
      success: true,
      data
    }
  } catch (error) {
    console.error('获取列表失败:', error)
    throw error
  }
}

/**
 * 创建邀请码
 */
async function createInviteCode(data, creatorOpenid) {
  const { code, rewardPoints, remark } = data

  // 验证参数
  if (!code || !/^[A-Z0-9]{6,12}$/.test(code)) {
    return {
      success: false,
      code: 400,
      message: '邀请码格式错误，必须是6-12位大写字母或数字'
    }
  }

  if (!rewardPoints || rewardPoints < 0) {
    return {
      success: false,
      code: 400,
      message: '奖励积分必须大于等于0'
    }
  }

  try {
    // 检查邀请码是否已存在
    const { data: existing } = await db.collection('invite_codes')
      .where({ code })
      .get()

    if (existing.length > 0) {
      return {
        success: false,
        code: 400,
        message: '该邀请码已存在，请使用其他邀请码'
      }
    }

    // 创建邀请码
    const inviteCodeData = {
      code,
      rewardPoints: parseInt(rewardPoints),
      remark: remark || '',
      status: 'active',
      createTime: new Date(),
      creatorId: creatorOpenid,
      usedCount: 0
    }

    await db.collection('invite_codes').add({
      data: inviteCodeData
    })

    return {
      success: true,
      message: '邀请码生成成功'
    }
  } catch (error) {
    console.error('创建邀请码失败:', error)
    throw error
  }
}

/**
 * 更新邀请码
 */
async function updateInviteCode(data) {
  const { id, rewardPoints, remark } = data

  if (!id) {
    return {
      success: false,
      code: 400,
      message: '缺少邀请码ID'
    }
  }

  if (!rewardPoints || rewardPoints < 0) {
    return {
      success: false,
      code: 400,
      message: '奖励积分必须大于等于0'
    }
  }

  try {
    await db.collection('invite_codes').doc(id).update({
      data: {
        rewardPoints: parseInt(rewardPoints),
        remark: remark || ''
      }
    })

    return {
      success: true,
      message: '更新成功'
    }
  } catch (error) {
    console.error('更新邀请码失败:', error)
    throw error
  }
}

/**
 * 切换状态
 */
async function toggleStatus(data) {
  const { id, status } = data

  if (!id || !status) {
    return {
      success: false,
      code: 400,
      message: '参数错误'
    }
  }

  if (!['active', 'disabled'].includes(status)) {
    return {
      success: false,
      code: 400,
      message: '状态值无效'
    }
  }

  try {
    await db.collection('invite_codes').doc(id).update({
      data: { status }
    })

    return {
      success: true,
      message: '状态更新成功'
    }
  } catch (error) {
    console.error('切换状态失败:', error)
    throw error
  }
}

/**
 * 删除邀请码
 */
async function deleteInviteCode(data) {
  const { id } = data

  if (!id) {
    return {
      success: false,
      code: 400,
      message: '缺少邀请码ID'
    }
  }

  try {
    await db.collection('invite_codes').doc(id).remove()

    return {
      success: true,
      message: '删除成功'
    }
  } catch (error) {
    console.error('删除邀请码失败:', error)
    throw error
  }
}

